﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using GalaSoft.MvvmLight.Command;
using Microsoft.Phone.Controls;
using MSH.Common.Classes;
using MSH.Common.DAO;
using MSH.Common.DAO.Results;
using WP7Client.Helpers;
using WP7Client.ServerManager;
using WP7Client.UserInterface.Pages;
using System.Collections.Generic;
using System.Windows.Media;

namespace WP7Client.Controller
{
    public class ProfileController : BaseController
    {
        #region Members

        private UserProfile _UserProfile;
        private String _Username;
        private String _FullName;
        private String _FirstName;

        private PivotItem ProfilePage;

        #endregion

        #region Get&Set

        public ICommand SaveProfileCommand
        {
            get;
            internal set;
        }

        public ICommand EditMobileNumberCommand
        {
            get;
            internal set;
        }

        public ICommand VerifyMobileNumberCommand
        {
            get;
            internal set;
        }

        public ICommand SendInvitationCommand
        {
            get;
            internal set;
        }

        public ICommand ChatCommand
        {
            get;
            internal set;
        }

        public UserProfile UserProfile
        {
            get { return _UserProfile; }
            set { _UserProfile = value; OnPropertyChanged("UserProfile"); }
        }

        public String FullName
        {
            get
            {
                if (UserProfile != null)
                    _FullName = UserProfile.FirstName + " " + UserProfile.SurName;
                return _FullName;
            }
        }

        public String Username
        {
            get { return _Username; }
            set { _Username = value; OnPropertyChanged("Username"); }
        }

        #endregion

        public ProfileController(PivotItem profilePage)
        {
            ProfilePage = profilePage;
            SaveProfileCommand = new RelayCommand(SaveProfile);
            EditMobileNumberCommand = new RelayCommand(EditMobileNumber);
            VerifyMobileNumberCommand = new RelayCommand(VerifyMobileNumber);
            ChatCommand = new RelayCommand<String>(ChatWith);
            SendInvitationCommand = new RelayCommand<String>(SendInvitation);
        }


        /// <summary>
        /// Haal het profiel op van een gebruiker
        /// </summary>
        /// <param name="username"></param>
        public void LoadUser(String username)
        {
            Loading = true;
            Username = username;
            HttpGet loadUserHttpGet = new HttpGet(String.Format(GlobalHelper.Url + "GetUserProfile/{0}/{1}", UserHelper.Token, username), typeof(GetUserProfileResult));
            loadUserHttpGet.FinishedGet += loadUserHttpGet_FinishedGet;
        }

        public override void Update()
        {
            base.Update();
            LoadUser(UserHelper.Username);
        }

        void loadUserHttpGet_FinishedGet(object sender, EventArgs e)
        {
            try
            {
                HttpGet get = sender as HttpGet;
                if (get == null || get.resultObject == null)
                    return; //Eventueel foutmelding

                UserProfile = (get.resultObject as GetUserProfileResult).UserProfile;

                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    ProfilePage.DataContext = null;

                    var root = App.Current.RootVisual as PhoneApplicationFrame;
                    if (root.Content is OverviewPage)
                    {
                        ProfilePage = (root.Content as OverviewPage).PivotItemMyProfile;
                    }
                    
                    if (UserProfile != null && UserProfile.SocialNetworkFields != null && UserProfile.SocialNetworkFields.Count > 0)
                    {
                        if (ProfilePage.Name.Equals("PivotItemMyProfile") || ProfilePage.Name.Equals("PivotItem"))
                        {
                            Grid g = (ProfilePage.Content as ListBox).Items[0] as Grid;

                            StackPanel sp = new StackPanel();
                            sp.SetValue(System.Windows.Controls.Grid.RowProperty, (g.RowDefinitions.Count - 1));
                            sp.Tag = "1337";
                            g.Children.Add(sp);

                            List<StackPanel> AccountTypeStackPanels = new List<StackPanel>();

                            foreach (SocialNetworkData snd in UserProfile.SocialNetworkFields)
                            {
                                StackPanel currentStackPanel = null;

                                foreach (StackPanel stackPanel in AccountTypeStackPanels)
                                {
                                    if (stackPanel.Name.Equals("stackPanel" + snd.AccountType))
                                    {
                                        currentStackPanel = stackPanel;
                                        break;
                                    }
                                }

                                if (currentStackPanel == null)
                                {
                                    currentStackPanel = new StackPanel();
                                    currentStackPanel.Name = "stackPanel" + snd.AccountType;
                                    TextBlock accountTypeHeader = new TextBlock() { Text = snd.AccountType, FontSize = 40, Style = (Style)Application.Current.Resources["TextBlockStyle"], Margin = new Thickness(10, 4, 0, 4) };
                                    Border border = new Border();
                                    border.Child = accountTypeHeader;
                                    border.Background = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
                                    currentStackPanel.Children.Add(border);
                                    AccountTypeStackPanels.Add(currentStackPanel);
                                }

                                TextBlock tb = new TextBlock() { Text = snd.FieldName + ":", Style = (Style)Application.Current.Resources["TextBlockStyle"] };
                                TextBlock tbv = new TextBlock() { Text = snd.Value, Margin = new Thickness(20, 0, 0, 0), Style = (Style)Application.Current.Resources["TextBlockStyle"] };
                                currentStackPanel.Children.Add(tb);
                                currentStackPanel.Children.Add(tbv);
                            }

                            foreach (StackPanel stackPanel in AccountTypeStackPanels)
                            {
                                sp.Children.Add(stackPanel);
                            }
                        }
                    }
                    else
                    {
                        if (ProfilePage.Name.Equals("PivotItemMyProfile") || ProfilePage.Name.Equals("PivotItem"))
                        {
                            Grid g = (ProfilePage.Content as ListBox).Items[0] as Grid;
                            UIElement element = null;
                            foreach (UIElement uie in g.Children)
                            {
                                if (uie is StackPanel && (uie as StackPanel).Tag != null && (uie as StackPanel).Tag.Equals("1337"))
                                {
                                    element = uie;
                                    break;
                                }
                            }

                            if (element != null)
                                g.Children.Remove(element);
                        }
                    }
                    ProfilePage.DataContext = this;                    
                });
            }
            finally
            {
                Loading = false;
            }
        }

        /// <summary>
        /// Sla de wijzigingen in het profiel op
        /// </summary>
        public void SaveProfile()
        {
            Loading = true;

            HttpGet saveProfileHttpGet = new HttpGet(
                String.Format(
                    GlobalHelper.Url +
                    "UpdateProfile/{0}?q1={1}&q2={2}&q3={3}&q4={4}&q5={5}&q6={6}&q7={7}&q8={8}&q9={9}",
                    UserHelper.Token, UserProfile.MobilePhoneNumber, UserProfile.FirstName, UserProfile.SurName, UserProfile.Address, UserProfile.Zipcode, UserProfile.City, System.Enum.GetName(typeof(GenderEnum), UserProfile.Sex), UserProfile.DateOfBirth, UserProfile.Website
                ),
            typeof(UpdateProfileResult), HttpGetMode.Mode1);
            saveProfileHttpGet.FinishedGet += saveProfileHttpGet_FinishedGet;
        }

        void saveProfileHttpGet_FinishedGet(object sender, EventArgs e)
        {
            try
            {
                HttpGet get = sender as HttpGet;
                if (get == null || get.resultObject == null)
                    return;

                UpdateProfileResult upr = get.resultObject as UpdateProfileResult;

            }
            catch (Exception ex)
            {

            }
            finally
            {
                Loading = false;
            }
        }

        /// <summary>
        /// Wijzig het mobiele nummer
        /// </summary>
        public void EditMobileNumber()
        {
            NavigationHelper.NavigateTo("/UserInterface/Pages/ChangeMobileNumberPage.xaml");
        }

        /// <summary>
        /// Verifier de wijziging van het mobiele nummer
        /// </summary>
        public void VerifyMobileNumber()
        {
            NavigationHelper.NavigateTo("/UserInterface/Pages/ActivateNewMobileNumberPage.xaml");
        }

        /// <summary>
        /// Chat met de gebruiker waarvan het profiel getoond word
        /// </summary>
        /// <param name="username">Gebruikersnaam van de gebruiker waarvan het profiel getoond word</param>
        private void ChatWith(String username)
        {
            ControllerHelper.ConversationsController.ChatWith(username);
        }

        /// <summary>
        /// Nodig de gebruiker waarvan het profiel getoond word uit als vriend
        /// </summary>
        /// <param name="username">Gebruikersnaam van de gebruiker waarvan het profiel getoond word</param>
        private void SendInvitation(String username) 
        {
            ControllerHelper.PeopleNearbyController.SendFriendInvitation(username);
        }
    }
}
